package com.editso.haier.security;

import com.editso.haier.dao.RoleDao;
import com.editso.haier.dao.UserDao;
import com.editso.haier.entity.Role;
import com.editso.haier.entity.User;
import com.editso.haier.util.Utils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.MutablePrincipalCollection;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;


@Component
public class UserRealm extends AuthorizingRealm {

    @Value("${haier.cookie-salt:haier-salt}")
    private String salt;

    @Value("${haier.no-login:false}")
    private boolean noLogin;

    private UserDao userDao;

    private RoleDao roleDao;


    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Autowired
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if (noLogin) {
            authorizationInfo.addRoles(
                    Utils.asList(roleDao.findAll()).stream().map(Role::getName).collect(Collectors.toList())
            );
            return authorizationInfo;
        }
        User user = userDao.findById(principalCollection.getPrimaryPrincipal().toString()).orElse(null);
        if (user == null) return null;
        authorizationInfo.addRoles(user.getRoles().stream().map(Role::getName).collect(Collectors.toList()));
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken passwordToken = ((UsernamePasswordToken) authenticationToken);
        User user = userDao.findByName(passwordToken.getUsername()).orElse(null);
        if (user == null) return null;
        return new SimpleAuthenticationInfo(
                user.getId(),
                user.getPassword(),
                ByteSource.Util.bytes(salt),
                getName()
        );
    }
}
